//
//  InabilityChooseView.swift
//  LongTermInsurance
//
//  Created by zolobdz on 2018/12/8.
//  Copyright © 2018年 HeChao. All rights reserved.
//

import UIKit
import ObjectMapper

class InabilityChooseView: UIView {

    lazy var homeDataOK = false
    lazy var orgDataOK = false
    lazy var zoneDataOK = false
    lazy var streetDataOK = false

    @IBOutlet weak var cityLocationLabel: UILabel!
    @IBOutlet weak var streetLocationLabel: UILabel!
    
    
    
    lazy var zoneArray: [ZoneModel] = {
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.zonesFileKey) as? [[String: Any]]{
            let array = Mapper<ZoneModel>().mapArray(JSONArray: dict)
            return array
        }
        return [ZoneModel]()
    }()
    
    lazy var streetArray: [StreetModel] = {
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.streetsFileKey) as? [[String: Any]]{
            let array = Mapper<StreetModel>().mapArray(JSONArray: dict)
            return array
        }
        return [StreetModel]()
    }()
    
    lazy var homeCareArray: [HomeCareModel] = {
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.homeCareFileKey) as? [[String: Any]]{
            let array = Mapper<HomeCareModel>().mapArray(JSONArray: dict)
            return array
        }
        return [HomeCareModel]()
    }()
    
    lazy var orgCareArray: [CareOrgModel] = {
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.orgCareFileKey) as? [[String: Any]]{
            let array = Mapper<CareOrgModel>().mapArray(JSONArray: dict)
            return array
        }
        return [CareOrgModel]()
    }()
    
    lazy var chooseORGModel: CareOrgModel? = {
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.orgCareChooseInfoKey) as? [String: Any] {
            let m = Mapper<CareOrgModel>().map(JSON: dict)
            return m
        }
        return nil
    }()
    
    lazy var chooseHomeModel: HomeCareModel? = {
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.homeCareChooseInfoKey) as? [String: Any] {
            let m = Mapper<HomeCareModel>().map(JSON: dict)
            return m
        }
        return nil
    }()
    
    lazy var chooseZoneModel: ZoneModel? = {
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.zoneChooseInfoKey) as? [String: Any] {
            let m = Mapper<ZoneModel>().map(JSON: dict)
            return m
        }
        return nil
    }()
    
    lazy var chooseStreetModel: StreetModel? = {
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.streetChooseInfoKey) as? [String: Any] {
            let m = Mapper<StreetModel>().map(JSON: dict)
            return m
        }
        return nil
    }()
    
    lazy var picker: CDInfoPickerView = {
        let picker = CDInfoPickerView()
        picker.isHidden = true
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(viewControllerEndEditing))
        picker.addGestureRecognizer(tap)
        picker.confirmButton.addTarget(self, action: #selector(pickerConfirmAction), for: .touchUpInside)
        return picker
    }()
    
    @IBOutlet weak var uploadPhotoButton: UIButton!
    @IBOutlet weak var chooseServiceButton: UIButton!
    
    @IBOutlet weak var serviceOrgButton: UIButton!
    @IBOutlet weak var homeCareButton: UIButton!
    
    @IBOutlet weak var methodNameLabel: UILabel!
    
    @IBOutlet weak var serviceNameLabel: UILabel!
    
    @IBOutlet weak var homeNameLabel: UILabel!
    
    
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    serviceOrgButton.setBackgroundImage(CDUtility.createImageWithColor(color: CDColor.themePink), for: .normal)
    serviceOrgButton.setBackgroundImage(CDUtility.createImageWithColor(color: .lightGray), for: .disabled)
    homeCareButton.setBackgroundImage(CDUtility.createImageWithColor(color: CDColor.themePink), for: .normal)
    homeCareButton.setBackgroundImage(CDUtility.createImageWithColor(color: .lightGray), for: .disabled)
        backgroundColor = CDColor.grayBackgroundColorA
        
        getData("") {
        }
        updateChoose()
    }
    
    @objc func pickerConfirmAction() {
        
        if let home = picker.result as? HomeCareModel {
            chooseHomeModel = home
            UserDefaults.standard.set(home.toJSON(), forKey: CDUserDefaultKey.homeCareChooseInfoKey)
            UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.orgCareChooseInfoKey)
        }
        
        if let org = picker.result as? CareOrgModel {
            chooseORGModel = org
            UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.homeCareChooseInfoKey)
            UserDefaults.standard.set(org.toJSON(), forKey: CDUserDefaultKey.orgCareChooseInfoKey)
        }
        
        if let zone = picker.result as? ZoneModel {
            chooseZoneModel = zone
            UserDefaults.standard.set(zone.toJSON(), forKey: CDUserDefaultKey.zoneChooseInfoKey)
            // 重新选择乡镇区划要重置街道区划
            UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.streetChooseInfoKey)
            chooseStreetModel = nil
        }
        
        if let street = picker.result as? StreetModel {
            chooseStreetModel = street
            UserDefaults.standard.set(street.toJSON(), forKey: CDUserDefaultKey.streetChooseInfoKey)
        }
        
        picker.hidePickerView()
        updateChoose()
    }
    
    func updateChoose() {
        if let home = chooseHomeModel {
            homeNameLabel.text = home.name
            
            self.homeCareButton.isEnabled = true
            self.serviceOrgButton.isEnabled = false
            self.methodNameLabel.text = "居家护理"
            self.methodNameLabel.isHidden = false
            self.homeNameLabel.isHidden = false
            self.serviceNameLabel.isHidden = true
        }
        
        if let org = chooseORGModel {
            serviceNameLabel.text = org.name
            
            self.homeCareButton.isEnabled = false
            self.serviceOrgButton.isEnabled = true
            self.methodNameLabel.text = "机构护理"
            self.methodNameLabel.isHidden = false
            self.homeNameLabel.isHidden = true
            self.serviceNameLabel.isHidden = false
        }
        
        if let zone = chooseZoneModel {
            cityLocationLabel.isHidden = false
            cityLocationLabel.text = zone.zoneName
            getStreetData(zone.zoneNum) { () -> (Void) in
                
            }
        }
        
        if let street = chooseStreetModel {
            streetLocationLabel.isHidden = false
            streetLocationLabel.text = street.streetName
        } else {
            streetLocationLabel.isHidden = true
            streetLocationLabel.text = ""
        }
    }
    
    @objc func viewControllerEndEditing(){
        UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
        if !picker.isHidden {
            picker.hidePickerView()
        }
    }

    @IBAction func uploadPhotoAction(_ sender: UIButton) {
        
        let vc = ChoosePhotoViewController()
        if let currentVC = CDUtility.currentViewController() {
            currentVC.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    
    @IBAction func chooseMethodAction(_ sender: UIButton) {
        if let currentVC = CDUtility.currentViewController() {
            let sheet = UIAlertController(title: "选择服务方式", message: "", preferredStyle: UIAlertControllerStyle.actionSheet)
            let action1 = UIAlertAction(title: "机构护理", style: UIAlertActionStyle.default) { (_) in
                self.homeCareButton.isEnabled = false
                self.serviceOrgButton.isEnabled = true
                self.methodNameLabel.text = "机构护理"
                self.methodNameLabel.isHidden = false
                self.homeNameLabel.isHidden = true
                self.serviceNameLabel.isHidden = false
            }
            let action2 = UIAlertAction(title: "居家护理", style: UIAlertActionStyle.default) { (_) in
                self.homeCareButton.isEnabled = true
                self.serviceOrgButton.isEnabled = false
                self.methodNameLabel.text = "居家护理"
                self.methodNameLabel.isHidden = false
                self.homeNameLabel.isHidden = false
                self.serviceNameLabel.isHidden = true
            }
            let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.default, handler: nil)
            sheet.addAction(action1)
            sheet.addAction(action2)
            sheet.addAction(cancel)
            
            
            let popover = sheet.popoverPresentationController;
            if (popover != nil) {
                popover?.sourceView = sender
                popover?.sourceRect = sender.bounds
                popover?.permittedArrowDirections = UIPopoverArrowDirection.any
            }
            
            currentVC.present(sheet, animated: true) {
            }
            
        }
    }
    
    @IBAction func chooseOrgAction(_ sender: UIButton) {
        if orgCareArray.isEmpty {
            return
        }
        
        self.endEditing(true)
        UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
        picker.firstInfoArray = orgCareArray
        picker.showPickerView()
    }
    
    @IBAction func homeCareAction(_ sender: UIButton) {
        if homeCareArray.isEmpty {
            return
        }
        
        self.endEditing(true)
        UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
        picker.firstInfoArray = homeCareArray
        picker.showPickerView()
    }
    
    @IBAction func cityLocationAction(_ sender: Any) {
        if zoneArray.isEmpty {
            return
        }
        
        self.endEditing(true)
        UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
        picker.firstInfoArray = zoneArray
        picker.showPickerView()
    }
    
    @IBAction func streetLocationAction(_ sender: Any) {
        if chooseZoneModel == nil || streetArray.isEmpty {
            makeToast("请先选择-乡镇区划")
            return
        }
        
        self.endEditing(true)
        UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
        picker.firstInfoArray = streetArray
        picker.showPickerView()
    }
}

extension InabilityChooseView {
    
    func getData(_ zoneNum: String, finished: @escaping ()->(Void)) {
//        if !homeCareArray.isEmpty &&
//            !orgCareArray.isEmpty {
//            homeDataOK = true
//            orgDataOK = true
//            finished()
//            return
//        }
        CDUtility.showHud()
        let values = ["jgfl": "118"].convertToJsonString()
        let paramString = "<json>"+values+"</json>"
        NetworkingHandle.fetchNetworkData(method: "getSNFInfo", paramString: paramString, success: {[weak self] (dict) in
            if let imgsString = dict["OrgDetail"] as? String {
                if let array = Mapper<HomeCareModel>().mapArray(JSONString: imgsString.lowercased()) {
                    self?.homeCareArray = array
                    self?.homeDataOK = true
                    
                    UserDefaults.standard.set(array.toJSON(), forKey: CDUserDefaultKey.homeCareFileKey)
                }
            }
            if let code = dict["ResultCode"] as? Int,code == 1 {
                if let msgString = dict["ResultMessage"] as? String {
                    CDUtility.showMSG(message: msgString)
                }
            }
            if self?.isOK(zoneNum) ?? false {
                finished()
            }
        }) { [weak self] in
            if self?.isOK(zoneNum) ?? false {
                finished()
            }
            print("")
        }
        
        
        let values1 = ["jgfl": "117"].convertToJsonString()
        let paramString1 = "<json>"+values1+"</json>"
        NetworkingHandle.fetchNetworkData(method: "getSNFInfo", paramString: paramString1, success: {[weak self] (dict) in
            if let imgsString = dict["OrgDetail"] as? String {
                if let array = Mapper<CareOrgModel>().mapArray(JSONString: imgsString.lowercased()) {
                    self?.orgCareArray = array
                    self?.orgDataOK = true
                    
                    UserDefaults.standard.set(array.toJSON(), forKey: CDUserDefaultKey.orgCareFileKey)
                }
            }
            if let code = dict["ResultCode"] as? Int,code == 1 {
                if let msgString = dict["ResultMessage"] as? String {
                    CDUtility.showMSG(message: msgString)
                }
            }
            if self?.isOK(zoneNum) ?? false {
                finished()
            }
        }) { [weak self] in
            if self?.isOK(zoneNum) ?? false {
                finished()
            }
        }
        
        let p2 = "<CodeName>"+"Zoninginfo"+"</CodeName>"
        let paramString2 = p2
        
        NetworkingHandle.oldfetchNetworkData(method: "ExeHNService", paramString: paramString2, success: {[weak self] (dict) in
            
            if let code = dict["Code"] as? Int,code == 0 {
                
                if let imgsString = dict["Message"] as? [[String: String]] {
                    let array = Mapper<ZoneModel>().mapArray(JSONArray: imgsString)
                    self?.zoneArray = array
                    self?.zoneDataOK = true
                
                    UserDefaults.standard.set(array.toJSON(), forKey: CDUserDefaultKey.zonesFileKey)
                }
                return
            }
            if let code = dict["Code"] as? Int,code == 1 {
                if let msgString = dict["Message"] as? String {
                    CDUtility.showMSG(message: msgString)
                }
            }
            if self?.isOK(zoneNum) ?? false {
                finished()
            }
        }) { [weak self] in
            if self?.isOK(zoneNum) ?? false {
                finished()
            }
            print("")
        }
        
    }
    
    func getStreetData(_ zoneNum: String, finished: @escaping ()->(Void)) {
        if zoneNum.count <= 0 {
            return
        }
        let p0 = ["ZoningNum": zoneNum]
        let p2 = "<CodeName>"+"streetinfo"+"</CodeName><json>\(p0.convertToJsonString())</json>"
        let paramString2 = p2
        
        NetworkingHandle.oldfetchNetworkData(method: "ExeHNService", paramString: paramString2, success: {[weak self] (dict) in
            
            if let code = dict["Code"] as? Int,code == 0 {
                if let imgsString = dict["Message"] as? [[String: String]] {
                    let array = Mapper<StreetModel>().mapArray(JSONArray: imgsString)
                    self?.streetArray = array
                    self?.streetDataOK = true
                    
                    UserDefaults.standard.set(array.toJSON(), forKey: CDUserDefaultKey.streetsFileKey)
                }
            }
            if let code = dict["Code"] as? Int,code == 1 {
                if let msgString = dict["Message"] as? String {
                    CDUtility.showMSG(message: msgString)
                }
            }
            if self?.isOK(zoneNum) ?? false {
                finished()
            }
        }) { [weak self] in
            if self?.isOK(zoneNum) ?? false {
                finished()
            }
            print("")
        }
    }
    
    func isOK(_ zoneNum: String) -> Bool {
        if homeDataOK && orgDataOK && zoneDataOK {
            if zoneNum.count > 0 {
                if streetDataOK {
                    CDUtility.hidHud()
                    return true
                }
            } else {
                CDUtility.hidHud()
                return true
            }
        }
        return false
    }
    
}
